#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time   : 2023-06-23 0:02
# @Author : hard work
# @File    : snmgV3_do_get_util.py
# @Description :
import time

from pysnmp.hlapi import *
from pysnmp.entity.rfc3413.oneliner import cmdgen

from test_app_main.case_cfg import snmp_oid_cfg
from common.remote_device_cfg import snmp_v3_config
from test_app_main.test_cases import case_10_1_check_port


def snmpV3_do_get(snmp_config, oid):
    try:
        cg = cmdgen.CommandGenerator()
        iterator = cg.getCmd(
            # UsmUserData(),
            UsmUserData(snmp_config[2][0],  # snmp用户名
                        snmp_config[2][1],  # 认证密码
                        snmp_config[2][2],  # 加密密码
                        authProtocol=usmHMACMD5AuthProtocol,  # 配置认证算法

                        # privProtocol=usm3DESEDEPrivProtocol)  # 配置加密算法
                        privProtocol=usmDESPrivProtocol),
            # UsmUserData(username, auth_key, priv_key,
            #             usmHMACSHAAuthProtocol, usmAesCfb128Protocol),
            UdpTransportTarget((snmp_config[0], snmp_config[1]), timeout=10, retries=1),
            oid)

        errorIndication, errorStatus, errorIndex, varBinds = iterator

        if errorIndication:  # SNMP engine errors
            print("errorIndication", errorIndication)
            return False
        else:
            if errorStatus:  # SNMP agent errors
                print('%s at %s' % (errorStatus.prettyPrint(), varBinds[int(errorIndex) - 1] if errorIndex else '?'))
                return False
            else:

                # for varBind in varBinds:  # SNMP response contents
                    # print([x.prettyPrint() for x in varBind])
                # print(varBinds[0][1])
                return varBinds[0][1]
    except Exception :
        return False

if __name__ == '__main__':
    # snmp_version = 2
    # snmp_config = snmp_v3_config()
    snmp_config = ["10.11.0.217", 161, ('hxz123456', 'hxz123456', 'hxz123456')]
    # snmp_case = case_10_snmp.get_port_status().items()
    # print(snmp_config)
    # for oid_name, oid_values in snmp_case.items():
    #     print("get to {} ...".format(oid_name))
    #     print(snmpV3_do_get(snmp_config, oid_values, snmp_version))
    ret = snmpV3_do_get(snmp_config, '1.3.6.1.2.1.2.2.1.7.17')
    print(ret)
    # flag = 0
    # while flag < 10:
    #     for i in range(1, 21):
    #         for k, v in snmp_oid_cfg.get_port_status().items():
    #             _val = snmpV3_do_get(snmp_config, v.format(i))
    #             # print(k + ':', _val)
    #             case_10_1_check_port.check_port_status(i, k, _val)
    #     flag += 1
    #     time.sleep(10)
